# -*- coding: utf-8 -*-
"""
Created on Sun Mar 28 09:42:46 2021

@author: Apple
"""


import sys
import os
from PyQt5.QtWidgets import (QMainWindow,QWidget,QTableWidget,QHBoxLayout,QMessageBox,QApplication,QTableWidgetItem)
from goodreads import Ui_MainWindow
import requests
from lxml import etree

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.tableWidget.resize(700,400) # 设置大小
        self.ui.tableWidget.move(24,52) # 设置位置
        
    def transBookName(self,bookName):
        bookCode = ''
        if bookName == '爱情':
            bookCode = 'romance'
        elif bookName == '恐怖':
            bookCode = 'horror'
        elif bookName =='科幻':
            bookCode = 'sci-fi'
        elif bookName == '历史':
            bookCode = 'historical'
        elif bookName =='幽默':
            bookCode = 'humorous'        
        return bookCode    
        
    def queryBook(self):
        # print("*querybook")
        bookName = self.ui.comboBox.currentText()
        bookCode = self.transBookName(bookName)
        
        url = 'https://www.goodreads.cc/'+bookCode+'/lastupdate_1.html' # 设置网址
        headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'}
        data = requests.get(url,headers=headers).text
        f = etree.HTML(data)
        books = f.xpath('//*[@id="diyax3"]/article/header/h2/a/text()') 
        authors = f.xpath('//*[@id="diyax3"]/article/p[1]/a/text()')
        notes = f.xpath('//*[@id="diyax3"]/article/p[3]/text()')
        
        tableWidget = self.ui.tableWidget
        tableWidget.setRowCount(20) # 设置行数
        tableWidget.setColumnCount(3) # 设置列数
        tableWidget.setHorizontalHeaderLabels(['author','title','note']) #设置表头
        tableWidget.resizeRowsToContents()
        for i in range(20):
            newItem = QTableWidgetItem(authors[i])
            tableWidget.setItem(i,0,newItem)
            
            newItem = QTableWidgetItem(books[i])
            tableWidget.setItem(i,1,newItem)
            
            newItem = QTableWidgetItem(notes[i])
            tableWidget.setItem(i,2,newItem)
        tableWidget.itemClicked.connect(self.getitem)
    
    def getitem(self,item):
        # print(item.text())
        result = item.text()
        self.ui.textEdit.setText(result)
        
    def clearResult(self):
        print("* clearResult")
        self.ui.tableWidget.clear()
        self.ui.textEdit.clear()
        tableWidget = self.ui.tableWidget
        tableWidget.setRowCount(0) # 设置行数
        tableWidget.setColumnCount(0) # 设置列数
        
    def savedata(self):
        tableWidget = self.ui.tableWidget
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        # print(os.getcwd())
        path = os.getcwd() + '/test.txt'
        path = path.replace('\\','/')
        with open(path,'a+') as f:
            f.seek(0)
            f.truncate()
        for i in range(numrow):
            for j in range(numcol):
                data = tableWidget.item(i,j).text()
                with open(path,'a+') as f:
                    f.write(data+'\n')
        
            
if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())